﻿using Abp.Dependency;
using RabbitMQ.GNClient;
using RabbitMQ.GNClient.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GN.Pay.Core.Tasks.Queue.Impl
{
    /// <summary>
    /// 
    /// </summary>
    abstract class AConsumerQueue<T> : AQueue, IConsumerQueue
    {
        /// <summary>
        /// 获取队列类型
        /// </summary>
        public QueueType QueueType { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="queueType"></param>
        /// <param name="iocManager"></param>
        public AConsumerQueue(QueueType queueType, IIocManager iocManager)
            : base(queueType.ToString())
        {
            this.IocManager = iocManager;
            this.QueueType = queueType;
        }

        /// <summary>
        /// 
        /// </summary>
        public IIocManager IocManager { get; private set; }

        public bool IsStarted { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        protected abstract ushort MaxPrefetchCount { get; }

        /// <summary>
        /// 
        /// </summary>
        protected virtual bool NoAck
        {
            get
            {
                return false;
            }
        }

        private IEventingConsumer eventingConsumer;

        /// <summary>
        /// 
        /// </summary>
        public void Start()
        {
            lock (this)
            {
                if (!IsStarted)
                {
                    if (eventingConsumer != null)
                    {
                        eventingConsumer.Received -= Consumer_Received;
                    }
                    var channel = GetChannel();
                    eventingConsumer = channel.CreateConsumer(MaxPrefetchCount, NoAck);
                    eventingConsumer.Received += Consumer_Received;
                    this.IsStarted = true;
                }
            }
        }

        protected override void Dispose(bool isDispose)
        {
            base.Dispose(isDispose);
            if (isDispose)
            {
                if (eventingConsumer != null)
                {
                    eventingConsumer.Received -= Consumer_Received;
                    eventingConsumer = null;
                }
            }
        }

        private void Consumer_Received(object sender, DeliverEventArgs e)
        {
            Consumer(sender as IEventingConsumer, SerializeUtils.Deserialize<T>(e.Message.Body, Encoding.UTF8), e);
        }

        protected abstract Task Consumer(IEventingConsumer eventConsumer, T data, DeliverEventArgs e);

        /// <summary>
        /// 延迟队列
        /// </summary>
        /// <param name="eventConsumer">队列</param>
        /// <param name="data">数据</param>
        /// <param name="delay">延迟时间</param>
        protected void DelayConsumer(IEventingConsumer eventConsumer, T data, DeliverEventArgs e, TimeSpan delay)
        {
            try
            {
                var queue = IocManager.Resolve<IQueueManager>();
                var msg = new ObjectMessage(data);                
                queue.Publish(this.QueueType, msg, delay);
                eventConsumer.Channel.Ack(e.DeliveryTag);
            }
            catch(Exception err)
            {
                Logger.Error("延迟队列出错:", err);
                eventConsumer.Channel.Nack(e.DeliveryTag, true);
            }
        }
    }
}
